package com.xudow.app.newui;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.activeshare.edu.ucenter.common.messages.user.UserDetailMessage;
import com.activeshare.edu.ucenter.models.user.UserProfileWithOther;
import com.mrwujay.cascade.activity.WheelActivity;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.xudow.app.Config;
import com.xudow.app.R;
import com.xudow.app.newui.base.BaseUiActivity;
import com.xudow.app.newui.dialog.BirthDateDialog;
import com.xudow.app.newui.dialog.HeadChoicePop;
import com.xudow.app.newui.dialog.SexChoicePop;
import com.xudow.app.newui.zutils.HeadChoiceUtils;
import com.xudow.app.newui.zutils.ZUtils;
import com.xudow.app.ui.task.PortraitUploadTask;
import com.xudow.app.ui.task.UserProfileTask;
import com.xudow.app.ui.task.user.ProfileEditTask;
import com.xudow.app.util.FileUtils;
import com.xudow.app.util.ImageUtils;


import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import butterknife.BindView;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * 作者：zhouXJ on 2016/4/6 15:56
 * 个人资料
 */
public class PersonalDataActivity extends BaseUiActivity implements View.OnClickListener,
        HeadChoicePop.HeadChoicePopListener, SexChoicePop.SexChoicePopListner {
    UserProfileWithOther profile;//用户对象

    @BindView(R.id.personal_data_sure_btn)
    TextView personal_data_sure_btn;

    @BindView(R.id.personal_data_head_choice_rl)
    RelativeLayout personal_data_head_choice_rl;

    @BindView(R.id.personal_data_head_choice_img)
    CircleImageView personal_data_head_choice_img;

    @BindView(R.id.personal_data_sex_choice_rl)
    RelativeLayout personal_data_sex_choice_rl;

    @BindView(R.id.personal_data_sex_choice_tv)
    TextView personal_data_sex_choice_tv;

    @BindView(R.id.personal_data_birth_choice_rl)
    RelativeLayout personal_data_birth_choice_rl;

    @BindView(R.id.personal_data_birth_choice_tv)
    TextView personal_data_birth_choice_tv;

    @BindView(R.id.personal_data_city_rl)
    RelativeLayout personal_data_city_rl;

    @BindView(R.id.personal_data_city_tv)
    TextView personal_data_city_tv;

    @BindView(R.id.personal_data_introd_ed)
    EditText personal_data_introd_ed;//简介

    @BindView(R.id.personal_data_nickname_tv)
    EditText personal_data_nickname_tv;//呢称

    @BindView(R.id.personal_data_phonenumber_et)
    TextView personal_data_phonenumber_et;//电话号码

    @BindView(R.id.personal_data_realname_et)
    EditText personal_data_realname_et;//真实姓名

    private DisplayImageOptions options;
    // 图片保存位置
    private Uri imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "image.jpg"));
    File imagfile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_data);

        updataInfor();
        //Log.e("onCreate: ", (null==profile)+""+profile.getPhotoPath());
    }

    @Override
    protected void initData() {


    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    /**
     * 更新用户数据
     */
    private void updataInfor(){
        profile=getMyApp().getProfile();
        //设置用户头像
        String url = String.format("%s%s?name=%s", Config.BASE_URL, Config.IMAGE_LOAD_URL, profile.getPhotoPath());
        ImageUtils.loadImage(this, personal_data_head_choice_img, url, R.mipmap.btn_profile_default_head_img);
        //设置手机号码
        personal_data_phonenumber_et.setText(profile.getMobilePhone());
        //设置真实姓名
        personal_data_realname_et.setText(profile.getName());
        if (null!=profile.getIsAuthent()&&"1".equals(profile.getIsAuthent())){//不可编辑
            personal_data_realname_et.setFocusable(false);
            personal_data_realname_et.setFocusableInTouchMode(false);
        }else {//可编辑
            personal_data_realname_et.setFocusable(true);
            personal_data_realname_et.setFocusableInTouchMode(true);
        }
        //呢称
        personal_data_nickname_tv.setText(profile.getNickName());
        //设置性别
        String gender="";
        if (profile.getGender()!=null){
            if (profile.getGender()==0)
                gender="不详";
            else if (profile.getGender()==1)
                gender="男";
            else if (profile.getGender()==2)
                gender="女";
        }
        personal_data_sex_choice_tv.setText(gender);
        //设置出生日期
        if (null!=profile.getBirthdayFormat())
            personal_data_birth_choice_tv.setText(profile.getBirthdayFormat());
        //设置城市
        if (null!=profile.getAddress())
            personal_data_city_tv.setText(profile.getAddress());
        if(null!=profile.getLabelName())
            personal_data_introd_ed.setText(profile.getLabelName());
    }
    // 返回键
    public void onBackBtnClick(View view) {
        finish();
    }


    @Override
    protected void initListener() {
        HeadChoicePop.getHeadChoicePopManager().setHeadChoicePopListener(this);
        SexChoicePop.getInstance().setOkClickListner(this);
        personal_data_sure_btn.setOnClickListener(this);
        personal_data_head_choice_rl.setOnClickListener(this);
        personal_data_sex_choice_rl.setOnClickListener(this);
        personal_data_birth_choice_rl.setOnClickListener(this);
        personal_data_city_rl.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.personal_data_sure_btn: // 确定
                //上传用户头像
                imagfile=new File(imageUri.getPath());
                if(imagfile.exists()) {
                    PortraitUploadTask portraitUploadTask = new PortraitUploadTask(this, profileUpdataHandler);
                    addTask(portraitUploadTask);
                    portraitUploadTask.execute(imageUri.getPath());
                }

                //修改基本基本资料
                HashMap<String,String> map=new HashMap<String, String>();
                String nickName=personal_data_nickname_tv.getText().toString().trim();
                String address=personal_data_city_tv.getText().toString().trim();
                String realName=personal_data_realname_et.getText().toString().trim();
                String gender=personal_data_sex_choice_tv.getText().toString().trim();
                String birthday=personal_data_birth_choice_tv.getText().toString().trim();
                String lable=personal_data_introd_ed.getText().toString().trim();
                if (TextUtils.isEmpty(nickName)){
                    getMyApp().makeToast("呢称不能为空");
                    return;
                }

                if (TextUtils.isEmpty(address)){
                    getMyApp().makeToast("地址不能为空");
                    return;
                }
                if (TextUtils.isEmpty(realName)){
                    getMyApp().makeToast("真实姓名不能为空");
                    return;
                }
                if (TextUtils.isEmpty(gender)){
                    getMyApp().makeToast("性别不能为空");
                    return;
                }else if (gender.equals("男")){
                    gender="1";
                }else if (gender.equals("女")){
                    gender="2";
                }else
                    gender="0";
                if (TextUtils.isEmpty(birthday)){
                    getMyApp().makeToast("生日不能为空");
                    return;
                }
                map.put("nick_name",nickName);
                map.put("address",address);
                map.put("name",realName);
                map.put("birthday",birthday);
                map.put("gender", gender);
                map.put("labelname", lable);
                ProfileEditTask profileEditTask=new ProfileEditTask(this,profileUpdataHandler);
                addTask(profileEditTask);
                profileEditTask.execute(map);

                break;

            case R.id.personal_data_head_choice_rl:  // 头像选择

                ZUtils.hideSoftInput(this);  // 如果软键盘显示 则隐藏
                HeadChoicePop.getHeadChoicePopManager().showPopupWindow(view, this);
                break;

            case R.id.personal_data_sex_choice_rl: // 性别选择
                ZUtils.hideSoftInput(this);  // 如果软键盘显示 则隐藏
                String sexStr = personal_data_sex_choice_tv.getText().toString();
                SexChoicePop.getInstance().showPopupWindow(view, this, sexStr);
                break;

            case R.id.personal_data_birth_choice_rl: // 生日选择
                ZUtils.hideSoftInput(this);  // 如果软键盘显示 则隐藏
                showBirthDialog();
                break;

            case R.id.personal_data_city_rl://城市选择
                ZUtils.hideSoftInput(this);
                //TODO 城市选择对话框
                startActivityForResult(new Intent(this, WheelActivity.class), GET_CITY_CODE);
                break;
        }
    }

    /**arg1=1为资料修改，2为头像上传
     * 修改用户资料和头像handler
     */
    private Handler profileUpdataHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what==ProfileEditTask.SUCCESS){
               // TODO 修改本地profile
               retrieveUserProfile();
                getMyApp().makeToast(msg.getData().getString("Message"));

            }else
                getMyApp().makeToast(msg.getData().getString("errMessage"));
        }
    };
    /**
     * 获取用户基本信息
     */
    private void retrieveUserProfile() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                UserProfileTask userProfileTask = new UserProfileTask(PersonalDataActivity.this,
                        userprofileHandler);
                userProfileTask.execute();
            }
        });
    }
    /**
     * 用户基本信息Handler
     */
    private Handler userprofileHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (UserProfileTask.SUCCESS == msg.what) {
                Bundle data = msg.getData();
                UserDetailMessage ud = (UserDetailMessage) data.getSerializable("profile");
                profile = ud.getUserDetail();
                //profile更新到本地
                getMyApp().setProfile(profile);

            } else {

                getMyApp().makeToast(msg.getData().getString("errMessage"));
            }
        }
    };

    /**
     * 显示生日选择对话框
     */
    private void showBirthDialog() {
        Calendar c = null;
        String birthStr = personal_data_birth_choice_tv.getText().toString();
        if (TextUtils.isEmpty(birthStr)) {
            c = Calendar.getInstance();
        } else {
            c = Calendar.getInstance();
            String data[] = birthStr.split("-");
            int currentYear = Integer.valueOf(data[0]).intValue();
            int currentMonth = Integer.valueOf(data[1]).intValue() - 1;
            int currentDay = Integer.valueOf(data[2]).intValue();
            c.set(currentYear, currentMonth, currentDay);
        }

        new BirthDateDialog(this, new BirthDateDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker startDatePicker, int startYear, int startMonthOfYear,
                                  int startDayOfMonth) {
                String textString = String.format("%d-%d-%d", startYear,
                        startMonthOfYear + 1, startDayOfMonth);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    Date date = sdf.parse(textString);
                    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
                    String time = format.format(date.getTime());
//                    modificationBirth(time); //  修改生日

                    long currentTime = System.currentTimeMillis();
                    long selectTime = date.getTime();
                    if (selectTime > currentTime) {
                        Toast.makeText(PersonalDataActivity.this, "不能选择当前时间以后的日期", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    personal_data_birth_choice_tv.setText(textString);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE), true).show();
    }

    private static final int TAKE_PICTURE_REQUEST_CODE = 80;
    private static final int CROP_PICTURE_REQUEST_CODE = 81;
    private static final int PHOTO_REQUEST_CODE = 82;
    public static final int GET_CITY_CODE=83;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == TAKE_PICTURE_REQUEST_CODE && resultCode == RESULT_OK) { // 剪切拍照的图片

            if (imageUri == null) {
                Toast.makeText(this, "图片路径出错", Toast.LENGTH_SHORT).show();
                return;
            }
            try {
                HeadChoiceUtils.getInstance().cropImageUri(this, imageUri, 200, 200, CROP_PICTURE_REQUEST_CODE, imageUri);
            } catch (Exception e) {
            }

        } else if (requestCode == PHOTO_REQUEST_CODE && resultCode == RESULT_OK) { // 剪切相册图片

            if (data != null) {
                Uri photoUri = data.getData();
                if (photoUri == null) {
                    Toast.makeText(this, "图片路径出错", Toast.LENGTH_SHORT).show();
                    return;
                }
                try {
                    HeadChoiceUtils.getInstance().cropImageUri(this, photoUri, 200, 200, CROP_PICTURE_REQUEST_CODE, imageUri);
                } catch (Exception e) {
                }
            }

        } else if (requestCode == CROP_PICTURE_REQUEST_CODE && resultCode == RESULT_OK) { // 显示剪切后的图片

            String imagePath = "file://" + imageUri.getPath();
            try {
                Bitmap bmp=HeadChoiceUtils.getBitmapFormUri(this,Uri.parse(imagePath));
                personal_data_head_choice_img.setImageBitmap(bmp);
            } catch (IOException e) {
                e.printStackTrace();
            }
            //ImageLoader.getInstance().displayImage(imagePath, personal_data_head_choice_img, options);
        }else if(requestCode == GET_CITY_CODE&& resultCode== RESULT_OK){
            if (null!=data){
                String city=data.getStringExtra("city");
                if (null!=city){
                    personal_data_city_tv.setText(city);
                }
            }
        }

    }

    /**
     * 打开照相机
     */
    @Override
    public void openCamera() {
        HeadChoiceUtils.getInstance().openCamera(this, TAKE_PICTURE_REQUEST_CODE, imageUri);
        HeadChoicePop.getHeadChoicePopManager().dismissPopWindow(this);

    }

    /**
     * 打开相册
     */
    @Override
    public void openPhoto() {
        HeadChoiceUtils.getInstance().openPhoto(this, PHOTO_REQUEST_CODE);
        HeadChoicePop.getHeadChoicePopManager().dismissPopWindow(this);
    }

    /**
     * 性别选择
     *
     * @param sexStr
     */
    @Override
    public void onOkClick(String sexStr) {
        personal_data_sex_choice_tv.setText(sexStr);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!HeadChoicePop.getHeadChoicePopManager().isShow() && !SexChoicePop.getInstance().isShow()) {
                finish();
            } else {
                HeadChoicePop.getHeadChoicePopManager().dismissPopWindow(this);
                SexChoicePop.getInstance().dismissPopWindow(this);
            }

            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

}
